//
//  ST_ConversationAdapter+IM.swift
//  btvideo
//
//  Created by Jason on 2022/1/19.
//  Copyright © 2022 JarvanZhang. All rights reserved.
//

import Foundation
import NIMSDK
import RxSwift


extension ST_ConversationAdapter{
    
    private typealias login_signal_input_type = (accid:String, token:String)
    
    /// 拿到IM token
    private func grab_IM_token_Signal(currentAccount:ST_BTAccountInfo)->Observable<login_signal_input_type>{
        
        if currentAccount.im_token.count > 1{
            
            print("ST_ConversationAdapter+IM  💐💐 im_token.count > 1")
            
            return Observable.just((accid:currentAccount.accid, token:currentAccount.im_token))
        }else{
            return TIANSession(requestUrl: PH.fetchIMTokenApi).wrap_response_data().map { json in
                
                print("ST_ConversationAdapter+IM  💐💐 pull IM  token =",json)
                
                let token = json["data"]["im_token"].stringValue
                
                TIANKeychain[SC.tian_im_token_key] = token
                
                return (accid:currentAccount.accid, token:token)
            }
        }
    }
    
    private func manual_login_i_m_signal(loginInfo:login_signal_input_type)->Observable<Void>{
        
        Observable<Void>.create { observer -> Disposable in
          
            
            print("ST_ConversationAdapter+IM  💐💐 NIMSDK login accid = ",loginInfo.accid,"💐💐",loginInfo.token)
            
            NIMSDK.shared().loginManager.login(loginInfo.accid, token: loginInfo.token) { error in
                
                if let e = error{
                    print("ST_ConversationAdapter+IM  💐💐 NIMSDK login error",e)
                    observer.onError(e)
                }else{
                    print("ST_ConversationAdapter+IM  💐💐 NIMSDK login success!!")
                    observer.onNext(())
                    observer.onCompleted()
                }
            }
            return Disposables.create()
            
         }
        
    }
    
    /// 拉取小助手消息
    private func pull_assistant_message(){
        
        guard let account = ST_BTUserInfoManager.shared.current_account_info,let is_register = ST_RegisterMonitor.shared.current_account_register_step_type_map[account.accid] else{
            return
        }
        
        TIANSession(requestUrl: PH.reportIMStatusApi, parameters: ["type":is_register ? 1 : 2]).wrap_response_data().retry(maxAttempts: 10, delay: 2).subscribe(onNext: { _ in
            
            print("ST_ConversationAdapter+IM  💐💐 拉取小助手成功!!")
            
        }).disposed(by: rx.disposeBag)
        
    }
    
    
}


extension ST_ConversationAdapter{
    
    func start_login_i_m_service(){
        
        cancellable_dispose_bag = nil
        
        guard let account = ST_BTUserInfoManager.shared.current_account_info else{
            return
        }
        
        let bag = DisposeBag()
        
        cancellable_dispose_bag = bag
        
        grab_IM_token_Signal(currentAccount: account).flatMapLatest(manual_login_i_m_signal).retry(maxAttempts: 1000, delay: 2).subscribe(onNext: {
            
            print("ST_ConversationAdapter+IM  💐💐 NIMSDK login success subscribed ")
            
        }).disposed(by: bag)
        
    }
    
    func logout_i_m_service(){
        
        cancellable_dispose_bag = nil
        
        NIMSDK.shared().loginManager.logout({ (error) in
            
            if let err = error{
                print("云信IM-- logout Error \(err)")
            }
        })
        
    }
    
    
}


extension ST_ConversationAdapter:NIMLoginManagerDelegate{
    
    func onLogin(_ step: NIMLoginStep) {
        
        if step == .syncOK{
            
            print("云信IM--数据同步完成؏؏☝ᖗ乛◡乛ᖘ☝؏؏ ؏؏☝ᖗ乛◡乛ᖘ☝؏؏")
            
            self.pull_assistant_message()
            
            self.refresh_all_data()
            
            _ = ST_DTChatFeed.shared
//            self.revert_last_status()
            
//            NotificationCenter.default.post(Notification.init(name: NSNotification.Name.i_msync_o_k))
            
        }
    }
    
    
    func onAutoLoginFailed(_ error: Error) {
        
        print("云信IM--AutoLoginError:",error)
    }
}
